package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.rocketmq.wxgroup.AddFriendReqDto;
import com.uzai.console.dto.rocketmq.wxgroup.KickGroupMemberDto;
import com.uzai.console.dto.rocketmq.wxgroup.WorkWxSetGroupManager;
import com.uzai.console.dto.wechatprivate.wxq.wxgroup.WxGroupIdDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroup.WxGroupQuery;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberBlacklistDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberIdDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberKickDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberQuery;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.AddManagerDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.DelManagerDto;
import com.uzai.console.dto.wechatwork.wxq.wxgroup.WxGroupMemberSetAdminDto;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.es.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.feign.WxContactsFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.service.wechatprivate.WxGroupMemberService;
import com.uzai.console.service.wechatprivate.WxGroupService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroup.WxGroupInfoVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupblacklist.baseconfig.WxqBlacklistBaseConfigVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupmember.WxGroupMemberInfoVo;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupmember.WxGroupMemberRelationVo;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人微信-微信群成员成员
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxGroupMemberServiceImpl implements WxGroupMemberService {

    Logger logger = LoggerFactory.getLogger(WxGroupMemberServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WxContactsFeignService wxContactsFeignService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxqGroupManagePlanMapper wxqGroupManagePlanMapper;
    @Autowired
    private WxqManagePlanMapper wxqManagePlanMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private WxGroupService wxGroupService;
    @Autowired
    private MerchantService merchantService;

    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;

    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;

    /**
     * 查询微信群成员列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberQuery
     * @return null
     */
    public Page<WxGroupMemberInfoVo> findWxGroupMemberList(WxGroupMemberQuery wxGroupMemberQuery, Boolean tuominFlag){

        if(StringUtils.isBlank(wxGroupMemberQuery.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupMemberQuery.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberQuery.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        //新建返回到页面的LIST对象
        List<WxGroupMemberInfoVo> wxGroupMemberInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxGroupMemberInfoVo> page = new Page<>();
        wxGroupMemberQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or_keyword = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxGroupMemberQuery.getMerId())));

        //微信群
        boolQuery.must(QueryBuilders.termQuery("groupWxid", esWxContacts.getWxid()));

        //微信群成员昵称
        if(StringUtils.isNotBlank(wxGroupMemberQuery.getNick())){
            boolQuery.must(QueryBuilders.matchQuery("nick",wxGroupMemberQuery.getNick()));
        }

        //微信群成员wxid
        if(StringUtils.isNotBlank(wxGroupMemberQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid",wxGroupMemberQuery.getWxid()));
        }

        //成员状态
        if(wxGroupMemberQuery.getStatus() != null){
            boolQuery.must(QueryBuilders.termQuery("status", wxGroupMemberQuery.getStatus()));
        }

        //邀请人微信id
        if(StringUtils.isNotBlank(wxGroupMemberQuery.getInviterWxid())){
            boolQuery.must(QueryBuilders.termQuery("inviterWxid", wxGroupMemberQuery.getInviterWxid()));
        }

        //关键词搜索-群昵称
        if(StringUtils.isNotBlank(wxGroupMemberQuery.getKeyword())){
            boolQuery_or_keyword.should(QueryBuilders.matchQuery("nick", wxGroupMemberQuery.getKeyword()));
            boolQuery_or_keyword.should(QueryBuilders.termQuery("wxid", wxGroupMemberQuery.getKeyword()));
        }

        searchSourceBuilder.query(boolQuery.must(boolQuery_or_keyword));

        //判断是否需要脱敏
        if(tuominFlag == null){
            tuominFlag = false;
        }
        String cmstype_wxcontacts_wxid_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_GROUP_MEMBER_WXID, wxGroupMemberQuery.getMerId()));
        if(StringUtils.isNotBlank(cmstype_wxcontacts_wxid_verified)){
            tuominFlag = false;
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_group_member = EsIndexName.UZAI_WX_GROUP_MEMBER;
        uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(uzai_wx_group_member, wxGroupMemberQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_wx_group_member, searchSourceBuilder, wxGroupMemberQuery.getSize(), wxGroupMemberQuery.getFromIndex(), null, null, null, wxGroupMemberQuery.getMerId());
        if(esResult.getTotalHits() == 0){ //查询不到数据，调用一次更新成员接口
            WxGroupIdDto wxGroupIdDto = new WxGroupIdDto();
            wxGroupIdDto.setMerId(wxGroupMemberQuery.getMerId());
            wxGroupIdDto.setId(wxGroupMemberQuery.getGroupId());
            wxGroupService.refreshGroupMember(wxGroupIdDto);
        }

        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxGroupMemberInfoVo wxGroupMemberInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxGroupMemberInfoVo.class);
                WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxGroupMemberInfoVo.getStatus());
                if(wxgroupMemberStatusEnum != null){
                    wxGroupMemberInfoVo.setStatusName(wxgroupMemberStatusEnum.getDesc());
                }

                try {
                    // 检查并设置拉黑原因
                    checkAndSetBlackReason(wxGroupMemberInfoVo);
                }catch (Exception e){

                }

                //会员信息
                if(StringUtils.isNotBlank(wxGroupMemberInfoVo.getWxid())){
                    User user = userService.findUserInfoByWxid(wxGroupMemberQuery.getMerId(), wxGroupMemberInfoVo.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    if(user != null){
                        wxGroupMemberInfoVo.setUserId(user.getId());
                        wxGroupMemberInfoVo.setBalance(user.getBalance());
                        wxGroupMemberInfoVo.setIntegral(user.getIntegral());
                    }
                }

                //ES查询通讯录
                SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                //运营商ID
                boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(wxGroupMemberQuery.getMerId())));
                //机器人微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWxContacts.getDeviceId()));
                //好友微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxGroupMemberInfoVo.getWxid()));
                searchSourceBuilder_contacts.query(boolQuery_contacts);
                WxGroupQuery wxGroupQuery = new WxGroupQuery();

                //通过查询运营商其他索引分片获取分片索引
                ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_wx_contacts, searchSourceBuilder_contacts, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, wxGroupMemberQuery.getMerId());
                if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                    wxGroupMemberInfoVo.setFriendFlag(1);
                }

                //查询是否是社群超级管理员
                String id_group = esWxContacts.getId() + "_" + wxGroupMemberInfoVo.getWxid();
                String id_all = esWxContacts.getMerId() + "_all_all_" + wxGroupMemberInfoVo.getWxid();
                Map<String,Object> map_group = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, id_group, null);
                Map<String,Object> map_all = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_SUPER_ADMIN, id_all, null);
                if(map_group != null || map_all != null){ //只要有一个不等于空
                    wxGroupMemberInfoVo.setSuperAdminFlag(1);
                }

                //是否脱敏处理
                wxGroupMemberInfoVo.setWxidNoTuomi(Tools.getStr(wxGroupMemberInfoVo.getWxid()));
                if(tuominFlag){
                    wxGroupMemberInfoVo.setWxid(DesensitizeUtil.around(Tools.getStr(wxGroupMemberInfoVo.getWxid()),3,3));
                }

                wxGroupMemberInfoVoList.add(wxGroupMemberInfoVo);
            }
        }

        //返回到页面分页对象
        page.setRecords(wxGroupMemberInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 获取被拉黑名单原因
     *
     * @param wxGroupMemberInfoVo
     * @return
     */
    private void checkAndSetBlackReason(WxGroupMemberInfoVo wxGroupMemberInfoVo) {

        Integer blackFlag = 0;
        Integer type = null;
        String remark = "";
        // 查询私有
        Map<String, Object> privateBlack = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxGroupMemberInfoVo.getId(), null);

        if (MapUtils.isNotEmpty(privateBlack)) {
            WxqBlacklistPrv wxPrivateBlack = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(privateBlack)), WxqBlacklistPrv.class);
            if (Objects.nonNull(wxPrivateBlack)) {
                type = wxPrivateBlack.getType();
                remark = wxPrivateBlack.getRemark();
                blackFlag = 1;
            }
        }
        // 如果为空,则查询全网黑名单
        else {
            Map<String,Object> publicBlack = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxGroupMemberInfoVo.getWxid(), null);
            if (MapUtils.isEmpty(publicBlack)) {
                wxGroupMemberInfoVo.setBlackout(blackFlag);
                return;
            }
            WxqWorkBlacklistPub wxPublicBlack  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(publicBlack)), WxqWorkBlacklistPub.class);
            if (Objects.nonNull(wxPublicBlack)) {
                type = wxPublicBlack.getType();
                remark = wxPublicBlack.getRemark();
                blackFlag = 1;
            }
        }

        StringBuilder blackReason = new StringBuilder("拉黑原因:");
        WxqBlacklistTypeEnum typeEnum = WxqBlacklistTypeEnum.getById(type);
        if (Objects.nonNull(typeEnum)) {
            blackReason.append(typeEnum.getDesc());
        }
        if (StringUtils.isNotBlank(remark)) {
            blackReason.append("(").append(remark).append(")");
        }
        wxGroupMemberInfoVo.setBlackoutReason(blackReason.toString());
        wxGroupMemberInfoVo.setBlackout(blackFlag);
    }

    /**
     * 踢出该群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberKickDto
     * @return null
     */
    @Transactional
    public void kickWxGroupMember(WxGroupMemberKickDto wxGroupMemberKickDto){

        if(StringUtils.isBlank(wxGroupMemberKickDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupMemberKickDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberKickDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        List<String> wxidList = wxGroupMemberKickDto.getWxidList();

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(wxidList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        //要踢掉的成员的wxid(多个wxid用;分割开 ,wxid数量显示 大于等于1,小于40)
        String arrWxids = wxidList.stream().collect(Collectors.joining(";"));

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupMemberKickDto.getMerId());
        if(deviceWechatInfo != null){

            //发送踢群指令MQ消息
            MsgDto<KickGroupMemberDto> msgDto = new MsgDto<>();
            KickGroupMemberDto kickGroupMemberDto = new KickGroupMemberDto();
            kickGroupMemberDto.setGroupId(esWxContacts.getWxid());
            kickGroupMemberDto.setArrWxids(arrWxids);
            msgDto.setContent(kickGroupMemberDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
            msgDto.setMerId(wxGroupMemberKickDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.KICK_GROUP_USER.getValue());
            noticeMsgPushProducerService.kickGroupUser(msgDto);

            //通过查询运营商其他索引分片获取分片索引
            String uzai_wx_group_member = EsIndexName.UZAI_WX_GROUP_MEMBER;
            uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(uzai_wx_group_member, wxGroupMemberKickDto.getMerId());
            //修改群成员状态
            for (String wxid : wxidList){
                //群成员id：merId_groupWxid_wxid
                String id = wxGroupMemberKickDto.getMerId() + "_" + esWxContacts.getWxid() + "_" + wxid;
                int now = DateUtil.getNowTime();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status",WxgroupMemberStatusEnum.KICKED.getValue()); //被踢
                jsonObject.put("quitTime", now);
                jsonObject.put("updateTime", now);
                //被踢原因
                if(StringUtils.isNotBlank(wxGroupMemberKickDto.getQuitReason())){
                    jsonObject.put("quitReason", wxGroupMemberKickDto.getQuitReason());
                }
                elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_group_member, id);
            }
        }
    }

    /**
     * 踢出该群
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberKickDto
     * @return null
     */
    @Transactional
    public void kickWxGroupMemberByMemberIdList(WxGroupMemberKickDto wxGroupMemberKickDto){

        if(StringUtils.isBlank(wxGroupMemberKickDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupMemberKickDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberKickDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        List<String> idList = wxGroupMemberKickDto.getIdList();

        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择成员微信id");
        }

        if(idList.size() >= 40){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "每次批量操作必须少于40个");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxGroupMemberKickDto.getMerId());
        List<String> wxidList = new ArrayList<>();
        for (String memberId : idList) {
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, memberId, null);
            EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
            if(esWxGroupMember != null){
                wxidList.add(esWxGroupMember.getWxid());
            }
        }

        if(wxidList == null || wxidList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到此群成员");
        }

        //要踢掉的成员的wxid(多个wxid用;分割开 ,wxid数量显示 大于等于1,小于40)
        String arrWxids = wxidList.stream().collect(Collectors.joining(";"));

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupMemberKickDto.getMerId());
        if(deviceWechatInfo != null){

            //发送踢群指令MQ消息
            MsgDto<KickGroupMemberDto> msgDto = new MsgDto<>();
            KickGroupMemberDto kickGroupMemberDto = new KickGroupMemberDto();
            kickGroupMemberDto.setGroupId(esWxContacts.getWxid());
            kickGroupMemberDto.setArrWxids(arrWxids);
            msgDto.setContent(kickGroupMemberDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
            msgDto.setMerId(wxGroupMemberKickDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.KICK_GROUP_USER.getValue());
            noticeMsgPushProducerService.kickGroupUser(msgDto);

            //修改群成员状态
            for (String wxid : wxidList){
                //群成员id：merId_groupWxid_wxid
                String id = wxGroupMemberKickDto.getMerId() + "_" + esWxContacts.getWxid() + "_" + wxid;
                int now = DateUtil.getNowTime();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("status",WxgroupMemberStatusEnum.KICKED.getValue()); //被踢
                jsonObject.put("quitTime", now);
                jsonObject.put("updateTime", now);
                //被踢原因
                if(StringUtils.isNotBlank(wxGroupMemberKickDto.getQuitReason())){
                    jsonObject.put("quitReason", wxGroupMemberKickDto.getQuitReason());
                }
                elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_wx_group_member, id);
            }
        }
    }

    /**
     * 添加好友
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberIdDto
     * @return null
     */
    public void addFriend(WxGroupMemberIdDto wxGroupMemberIdDto){

        if(StringUtils.isBlank(wxGroupMemberIdDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupMemberIdDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberIdDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxGroupMemberIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询该成员信息
        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxGroupMemberIdDto.getMerId());
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, wxGroupMemberIdDto.getId(), null);
        EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
        if(esWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupMemberIdDto.getMerId());
        if(deviceWechatInfo != null){
            //发送添加好友MQ消息
            MsgDto<AddFriendReqDto> msgDto = new MsgDto<>();
            AddFriendReqDto addFriendReqDto = new AddFriendReqDto();
            addFriendReqDto.setWxid(esWxGroupMember.getWxid());
            addFriendReqDto.setV2(esWxContacts.getWxid()); //群wxid
            addFriendReqDto.setVerifyMsg("");
            msgDto.setContent(addFriendReqDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
            msgDto.setMerId(wxGroupMemberIdDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.ADD_FRIEND_REQ.getValue());
            noticeMsgPushProducerService.addFriendReq(msgDto);
        }
    }

    /**
     * 加入黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberBlacklistDto
     * @return null
     */
    public void addBlacklist(WxGroupMemberBlacklistDto wxGroupMemberBlacklistDto){
        if(StringUtils.isBlank(wxGroupMemberBlacklistDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupMemberBlacklistDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberBlacklistDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxGroupMemberBlacklistDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入成员主键id");
        }

        //查询该成员信息
        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxGroupMemberBlacklistDto.getMerId());
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, wxGroupMemberBlacklistDto.getId(), null);
        EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
        if(esWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_groupWxid_wxid
        String id = wxGroupMemberBlacklistDto.getId();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, id, null);
        WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
        if(wxqBlacklistPrv != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员已经在黑名单中");
        }

        //添加到全网黑名单
        if(wxGroupMemberBlacklistDto.getAllBackFlag() != null && wxGroupMemberBlacklistDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, esWxGroupMember.getWxid(), null);
            WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
            if(wxqBlacklistPub != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员已经在共享黑名单里");
            }
        }

        //添加到全网黑名单
        if(wxGroupMemberBlacklistDto.getAllBackFlag() != null && wxGroupMemberBlacklistDto.getAllBackFlag().intValue() == 1){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, esWxGroupMember.getWxid(), null);
            WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
            //全网黑名单中不存在
            if(wxqBlacklistPub == null){
                wxqBlacklistPub = new WxqBlacklistPub();
                wxqBlacklistPub.setId(esWxGroupMember.getWxid());
                wxqBlacklistPub.setMerId(esWxGroupMember.getMerId());
                wxqBlacklistPub.setGroupWxid(esWxGroupMember.getGroupWxid());
                wxqBlacklistPub.setWxid(esWxGroupMember.getWxid());
                wxqBlacklistPub.setNick(esWxGroupMember.getNick());
                wxqBlacklistPub.setHimg(esWxGroupMember.getHimg());
                wxqBlacklistPub.setType(wxGroupMemberBlacklistDto.getType());
                wxqBlacklistPub.setRemark(wxGroupMemberBlacklistDto.getRemark());
                wxqBlacklistPub.setCreateTime(now);
                wxqBlacklistPub.setUpdateTime(now);
                //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                wxqBlacklistPub.setSource(0);
                //增加到全网黑名单
                elasticsearchUtil.addData(wxqBlacklistPub, EsIndexName.UZAI_WXQ_BLACKLIST_PUB, esWxGroupMember.getWxid());
            }
        }

        //拉群范围
        List<WxGroupMemberKickDto> wxGroupMemberKickDtoList = new ArrayList<>(); //封装踢群人数
        if(wxGroupMemberBlacklistDto.getRange() == 0){//本群拉黑
            //拉入群黑名单
            wxqBlacklistPrv = new WxqBlacklistPrv();
            wxqBlacklistPrv.setId(id);
            wxqBlacklistPrv.setMerId(esWxGroupMember.getMerId());
            wxqBlacklistPrv.setGroupWxid(esWxGroupMember.getGroupWxid());
            wxqBlacklistPrv.setWxid(esWxGroupMember.getWxid());
            wxqBlacklistPrv.setNick(esWxGroupMember.getNick());
            wxqBlacklistPrv.setHimg(esWxGroupMember.getHimg());
            wxqBlacklistPrv.setType(wxGroupMemberBlacklistDto.getType());
            wxqBlacklistPrv.setRemark(wxGroupMemberBlacklistDto.getRemark());
            wxqBlacklistPrv.setCreateTime(now);
            wxqBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wxqBlacklistPrv, EsIndexName.UZAI_WXQ_BLACKLIST_PRV, id);

            //加入是否踢群临时列表
            WxGroupMemberKickDto wxGroupMemberKickDto = new WxGroupMemberKickDto();
            wxGroupMemberKickDto.setMerId(wxGroupMemberBlacklistDto.getMerId());
            wxGroupMemberKickDto.setGroupId(wxGroupMemberBlacklistDto.getGroupId());
            List<String> wxidList = new ArrayList<>();
            wxidList.add(esWxGroupMember.getWxid());
            wxGroupMemberKickDto.setWxidList(wxidList);
            wxGroupMemberKickDto.setQuitReason("加入黑名单，自动踢出该群");
            wxGroupMemberKickDtoList.add(wxGroupMemberKickDto);

        }else{//全部群拉黑
            //调用有群里方案的个人微信群
            WxGroupQuery wxGroupQuery = new WxGroupQuery();
            wxGroupQuery.setMerId(wxGroupMemberBlacklistDto.getMerId());
            wxGroupQuery.setUserType(1); //个人微信群
            wxGroupQuery.setManagePlanIdFlag(1); //过滤未配置管理方案的群
            //执行分页查询对象
            wxGroupQuery.setSize(10);
            int currentPage = 1;
            wxGroupQuery.setCurrent(currentPage);

            //查询总数
            Page<WxGroupInfoVo> wxGroupInfoVoPage = wxGroupService.findWxGroupList(wxGroupQuery);
            while(wxGroupInfoVoPage != null && wxGroupInfoVoPage.getRecords() != null && wxGroupInfoVoPage.getRecords().size() > 0){
                for(WxGroupInfoVo wxGroupInfoVo : wxGroupInfoVoPage.getRecords()){
                    //查询该成员信息
                    String id_tmp = wxGroupMemberBlacklistDto.getMerId() + "_" + wxGroupInfoVo.getWxid() + "_" + esWxGroupMember.getWxid();
                    Map<String,Object> dataMp_member_tmp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, id_tmp, null);
                    EsWxGroupMember esWxGroupMember_tmp  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member_tmp)), EsWxGroupMember.class);
                    //拉入群黑名单
                    wxqBlacklistPrv = new WxqBlacklistPrv();
                    wxqBlacklistPrv.setId(id_tmp);
                    wxqBlacklistPrv.setMerId(esWxGroupMember.getMerId());
                    wxqBlacklistPrv.setGroupWxid(wxGroupInfoVo.getWxid());
                    wxqBlacklistPrv.setWxid(esWxGroupMember.getWxid());
                    wxqBlacklistPrv.setNick(esWxGroupMember.getNick());
                    wxqBlacklistPrv.setHimg(esWxGroupMember.getHimg());
                    wxqBlacklistPrv.setType(wxGroupMemberBlacklistDto.getType());
                    wxqBlacklistPrv.setRemark(wxGroupMemberBlacklistDto.getRemark());
                    wxqBlacklistPrv.setCreateTime(now);
                    wxqBlacklistPrv.setUpdateTime(now);
                    elasticsearchUtil.addData(wxqBlacklistPrv, EsIndexName.UZAI_WXQ_BLACKLIST_PRV, id_tmp);

                    //加入是否踢群临时列表
                    if(esWxGroupMember_tmp != null && esWxGroupMember_tmp.getStatus() == WxgroupMemberStatusEnum.NORMAL.getValue().intValue()){
                        WxGroupMemberKickDto wxGroupMemberKickDto = new WxGroupMemberKickDto();
                        wxGroupMemberKickDto.setMerId(esWxGroupMember_tmp.getMerId());
                        String groupId_tmp = esWxGroupMember_tmp.getMerId() + "_" + wxGroupInfoVo.getDeviceId() + "_" + wxGroupInfoVo.getWxid();
                        wxGroupMemberKickDto.setGroupId(groupId_tmp);
                        List<String> wxidList = new ArrayList<>();
                        wxidList.add(esWxGroupMember_tmp.getWxid());
                        wxGroupMemberKickDto.setWxidList(wxidList);
                        wxGroupMemberKickDto.setQuitReason("加入黑名单，自动踢出该群");
                        wxGroupMemberKickDtoList.add(wxGroupMemberKickDto);
                    }
                }
                //循环查询下一页
                currentPage ++ ;
                wxGroupQuery.setCurrent(currentPage);
                wxGroupInfoVoPage = wxGroupService.findWxGroupList(wxGroupQuery);
            }
        }

        //判断踢群列表
        if(wxGroupMemberKickDtoList != null && wxGroupMemberKickDtoList.size() > 0){
            //判断是否将此人踢群，根据社群黑名单是否勾选了加入黑名单成员，是否自动踢出群
            MerBaseConfig wxq_blacklist_config = merBaseConfigMapper.selectByMerId(wxGroupMemberBlacklistDto.getMerId(), MerConfigKeyEnum.WXQ_BLACKLIST_CONFIG.getValue());
            if(wxq_blacklist_config != null && StringUtils.isNotBlank(wxq_blacklist_config.getVal())){
                WxqBlacklistBaseConfigVo wxqBlacklistBaseConfigVo =  JSONObject.parseObject(wxq_blacklist_config.getVal(), WxqBlacklistBaseConfigVo.class);
                //勾选了自动踢群选项，则执行踢群操作
                if(wxqBlacklistBaseConfigVo.getAutoKickFlag() != null && wxqBlacklistBaseConfigVo.getAutoKickFlag().intValue() == 1){
                    for(WxGroupMemberKickDto wxGroupMemberKickDto: wxGroupMemberKickDtoList){
                        try {
                            kickWxGroupMember(wxGroupMemberKickDto);
                        }catch (Exception e){
                            logger.error("---加入黑名单----error={}", e.getMessage());
                        }
                    }
                }
            }
        }
    }

    /**
     * 查询邀请关系
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxGroupMemberIdDto
     * @return null
     */
    public WxGroupMemberRelationVo findInviteRelation(WxGroupMemberIdDto wxGroupMemberIdDto){
        WxGroupMemberRelationVo wxGroupMemberRelationVo = new WxGroupMemberRelationVo();

        if(StringUtils.isBlank(wxGroupMemberIdDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxGroupMemberIdDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberIdDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        if(StringUtils.isBlank(wxGroupMemberIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主键id");
        }

        //查询该成员信息
        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxGroupMemberIdDto.getMerId());
        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, wxGroupMemberIdDto.getId(), null);
        EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
        if(esWxGroupMember == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该成员不存在");
        }

        BeanUtils.copyProperties(esWxGroupMember, wxGroupMemberRelationVo);

        WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxGroupMemberRelationVo.getStatus());
        if(wxgroupMemberStatusEnum != null){
            wxGroupMemberRelationVo.setStatusName(wxgroupMemberStatusEnum.getDesc());
        }

        //会员信息
        if(StringUtils.isNotBlank(wxGroupMemberRelationVo.getWxid())){
            User user = userService.findUserInfoByWxid(esWxContacts.getMerId(), wxGroupMemberRelationVo.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
            if(user != null){
                wxGroupMemberRelationVo.setUserId(user.getId());
                wxGroupMemberRelationVo.setBalance(user.getBalance());
                wxGroupMemberRelationVo.setIntegral(user.getIntegral());
            }else{
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(wxGroupMemberRelationVo.getWxid());
                if(deviceWechatInfo != null){
                    wxGroupMemberRelationVo.setDeviceUniqueId(deviceWechatInfo.getId());
                }
            }
        }

        //ES查询通讯录-是否
        SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWxContacts.getMerId())));
        //机器人微信id
        boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWxContacts.getDeviceId()));
        //好友微信id
        boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxGroupMemberRelationVo.getWxid()));
        searchSourceBuilder_contacts.query(boolQuery_contacts);
        WxGroupQuery wxGroupQuery = new WxGroupQuery();
        ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_wx_contacts, searchSourceBuilder_contacts, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, esWxContacts.getMerId());
        if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
            wxGroupMemberRelationVo.setFriendFlag(1);
        }


        //递归查询下级
        List<WxGroupMemberRelationVo> sonList = getSonList(wxGroupMemberRelationVo, esWxContacts,20);
        wxGroupMemberRelationVo.setSonList(sonList);

        //递归查询上级
        List<WxGroupMemberRelationVo> parentList = new ArrayList<>();
        getParentList(parentList, wxGroupMemberRelationVo, esWxContacts,20);
        Collections.reverse(parentList);
        wxGroupMemberRelationVo.setParentList(parentList);
        return wxGroupMemberRelationVo;
    }

    /**
     * 递归查询下级成员
     * @param wxGroupMemberRelationVo 群成员
     * @param esWxContacts 群消息
     * @param esWxContacts optTimes 递归次数控制参数，最大支持50次，防止死循环，造成内存溢出
     * @return
     */
    private List<WxGroupMemberRelationVo> getSonList(WxGroupMemberRelationVo wxGroupMemberRelationVo, EsWxContacts esWxContacts, int optTimes) {
        //只递归50次，防止数据溢出造成死循环
        if(optTimes <= 0){
            return  null;
        }

        //执行一次，就减少一次
        optTimes--;

        List<WxGroupMemberRelationVo> wxGroupMemberRelationVoList = new ArrayList<>();
        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", esWxContacts.getMerId()));
        //微信群
        boolQuery.must(QueryBuilders.termQuery("groupWxid", wxGroupMemberRelationVo.getGroupWxid()));
        //邀请人微信id
        boolQuery.must(QueryBuilders.termQuery("inviterWxid", wxGroupMemberRelationVo.getWxid()));
        searchSourceBuilder.query(boolQuery);
        WxGroupMemberQuery wxGroupMemberQuery = new WxGroupMemberQuery();
        wxGroupMemberQuery.setMerId(esWxContacts.getMerId());

        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, esWxContacts.getMerId());
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, esWxContacts.getMerId());

        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_wx_group_member, searchSourceBuilder, wxGroupMemberQuery.getSize(), wxGroupMemberQuery.getFromIndex(), null, null, null, esWxContacts.getMerId());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxGroupMemberRelationVo wxGroupMemberRelationVo_son  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxGroupMemberRelationVo.class);
                if(wxGroupMemberRelationVo_son != null){
                    WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxGroupMemberRelationVo_son.getStatus());
                    if(wxgroupMemberStatusEnum != null){
                        wxGroupMemberRelationVo_son.setStatusName(wxgroupMemberStatusEnum.getDesc());
                    }

                    //会员信息
                    if(StringUtils.isNotBlank(wxGroupMemberRelationVo_son.getWxid())) {
                        User user = userService.findUserInfoByWxid(esWxContacts.getMerId(), wxGroupMemberRelationVo_son.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                        if (user != null) {
                            wxGroupMemberRelationVo_son.setUserId(user.getId());
                            wxGroupMemberRelationVo_son.setBalance(user.getBalance());
                            wxGroupMemberRelationVo_son.setIntegral(user.getIntegral());
                        }else{
                            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(wxGroupMemberRelationVo_son.getWxid());
                            if (deviceWechatInfo != null) {
                                wxGroupMemberRelationVo_son.setDeviceUniqueId(deviceWechatInfo.getId());
                            }
                        }
                    }

                    //ES查询通讯录-是否
                    SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                    BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                    //运营商ID
                    boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWxContacts.getMerId())));
                    //机器人微信id
                    boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWxContacts.getDeviceId()));
                    //好友微信id
                    boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxGroupMemberRelationVo_son.getWxid()));
                    searchSourceBuilder_contacts.query(boolQuery_contacts);
                    WxGroupQuery wxGroupQuery = new WxGroupQuery();
                    ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_wx_contacts, searchSourceBuilder_contacts, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, esWxContacts.getMerId());
                    if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                        wxGroupMemberRelationVo_son.setFriendFlag(1);
                    }
                    //递归查询下级
                    List<WxGroupMemberRelationVo> sonList = getSonList(wxGroupMemberRelationVo_son, esWxContacts, optTimes);
                    wxGroupMemberRelationVo_son.setSonList(sonList);
                    wxGroupMemberRelationVoList.add(wxGroupMemberRelationVo_son);
                }
            }
        }
        return wxGroupMemberRelationVoList;
    }

    /**
     * 递归查询上级成员
     * @param wxGroupMemberRelationVo 成员信息
     * @param optTimes  optTimes 递归次数控制参数，最大支持50次，防止死循环，造成内存溢出
     * @return
     */
    private void getParentList(List<WxGroupMemberRelationVo> wxGroupMemberInfoVoList, WxGroupMemberRelationVo wxGroupMemberRelationVo, EsWxContacts esWxContacts, int optTimes) {

        //只递归50次，防止数据溢出造成死循环
        if(optTimes <= 0){
            return;
        }

        //执行一次，就减少一次
        optTimes--;

        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, esWxContacts.getMerId());
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, esWxContacts.getMerId());


        //有上级
        if(StringUtils.isNotBlank(wxGroupMemberRelationVo.getInviterWxid())){
            //查询该成员信息merId_groupWxid_wxid
            String id = esWxContacts.getMerId() + "_" + wxGroupMemberRelationVo.getGroupWxid() + "_" + wxGroupMemberRelationVo.getInviterWxid();
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, id, null);
            WxGroupMemberRelationVo wxGroupMemberRelationVo_parent  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), WxGroupMemberRelationVo.class);
            if(wxGroupMemberRelationVo_parent != null){
                WxgroupMemberStatusEnum wxgroupMemberStatusEnum = WxgroupMemberStatusEnum.getValue(wxGroupMemberRelationVo_parent.getStatus());
                if(wxgroupMemberStatusEnum != null){
                    wxGroupMemberRelationVo_parent.setStatusName(wxgroupMemberStatusEnum.getDesc());
                }

                //会员信息
                if(StringUtils.isNotBlank(wxGroupMemberRelationVo_parent.getWxid())){
                    User user = userService.findUserInfoByWxid(esWxContacts.getMerId(), wxGroupMemberRelationVo_parent.getWxid(), DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    if(user != null){
                        wxGroupMemberRelationVo_parent.setUserId(user.getId());
                        wxGroupMemberRelationVo_parent.setBalance(user.getBalance());
                        wxGroupMemberRelationVo_parent.setIntegral(user.getIntegral());
                    }else{
                        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(wxGroupMemberRelationVo_parent.getWxid());
                        if(deviceWechatInfo != null){
                            wxGroupMemberRelationVo_parent.setDeviceUniqueId(deviceWechatInfo.getId());
                        }
                    }
                }

                //ES查询通讯录-是否
                SearchSourceBuilder searchSourceBuilder_contacts = new SearchSourceBuilder();
                BoolQueryBuilder boolQuery_contacts = QueryBuilders.boolQuery();
                //运营商ID
                boolQuery_contacts.must(QueryBuilders.termQuery("merId", Tools.getLong(esWxContacts.getMerId())));
                //机器人微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("deviceId", esWxContacts.getDeviceId()));
                //好友微信id
                boolQuery_contacts.must(QueryBuilders.termQuery("wxid", wxGroupMemberRelationVo_parent.getWxid()));
                searchSourceBuilder_contacts.query(boolQuery_contacts);
                WxGroupQuery wxGroupQuery = new WxGroupQuery();
                ESResult esResult_contacts = elasticsearchUtilGroupMsg.searchListData(uzai_wx_contacts, searchSourceBuilder_contacts, wxGroupQuery.getSize(), wxGroupQuery.getFromIndex(), null, null, null, esWxContacts.getMerId());
                if(esResult_contacts != null && esResult_contacts.getTotalHits() > 0){
                    wxGroupMemberRelationVo_parent.setFriendFlag(1);
                }
                wxGroupMemberInfoVoList.add(wxGroupMemberRelationVo_parent);
                //递归查询
                getParentList(wxGroupMemberInfoVoList, wxGroupMemberRelationVo_parent, esWxContacts, optTimes);
            }
        }
    }

    public void setAdmin(WxGroupMemberSetAdminDto wxGroupMemberSetAdminDto){

        if(wxGroupMemberSetAdminDto.getOptType() != 1 && wxGroupMemberSetAdminDto.getOptType() != 2){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "操作类型不正确");
        }

        if(StringUtils.isBlank(wxGroupMemberSetAdminDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, wxGroupMemberSetAdminDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, wxGroupMemberSetAdminDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(esWxContacts.getDeviceUniqueId(), wxGroupMemberSetAdminDto.getMerId());
        if(deviceWechatInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该企业微信群机器人未找到");
        }

        //成员id列表
        List<String> wxidList = new ArrayList<>();
        List<String> idList = wxGroupMemberSetAdminDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "成员id列表为空");
        }

        for (String id : idList) {
            //查询
            String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxGroupMemberSetAdminDto.getMerId());
            //查询该成员信息
            Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, id, null);
            EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
            if (esWxGroupMember != null && !StringUtils.isBlank(esWxGroupMember.getWxid())) {
                wxidList.add(esWxGroupMember.getWxid());
            }
        }

        if (!wxidList.isEmpty()) {
            //调用设置群成员管理员接口
            MsgDto<WorkWxSetGroupManager> msgDto = new MsgDto<>();
            WorkWxSetGroupManager workWxSetGroupManager = new WorkWxSetGroupManager();
            workWxSetGroupManager.setGroupId(esWxContacts.getWxid());
            workWxSetGroupManager.setArrWxids(String.join(";", wxidList));
            workWxSetGroupManager.setOptType(wxGroupMemberSetAdminDto.getOptType());
            msgDto.setContent(workWxSetGroupManager);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(wxGroupMemberSetAdminDto.getMerId());
            msgDto.setMsgType(MessageFuncEnum.SET_GROUP_MANAGER.getValue());
            //调用微服务
            UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.workwxSetgroupManager(msgDto);
            logger.info("--调用设置群成员管理员接口--para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));
            if (uzaiRespVo != null && uzaiRespVo.getCode() != 200) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, uzaiRespVo.getMsg());
            }
        }


    }


    @Override
    public void addManager(AddManagerDto addManagerDto) {
        if(StringUtils.isBlank(addManagerDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }
        if(addManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(addManagerDto.getWxidList()==null||addManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        if(addManagerDto.getWxidList().size()>3){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最多设置3个管理员");
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, addManagerDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, addManagerDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        WxGroupMemberSetAdminDto wxGroupMemberSetAdminDto=new WxGroupMemberSetAdminDto();
        wxGroupMemberSetAdminDto.setMerId(addManagerDto.getMerId());
        wxGroupMemberSetAdminDto.setGroupId(addManagerDto.getGroupId());
        wxGroupMemberSetAdminDto.setOptType(1);
        wxGroupMemberSetAdminDto.setIdList(addManagerDto.getWxidList());
        setAdmin(wxGroupMemberSetAdminDto);
    }

    @Override
    public void delManager(DelManagerDto delManagerDto) {
        if(StringUtils.isBlank(delManagerDto.getGroupId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择微信群");
        }
        if(delManagerDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "运营商ID不能为空");
        }
        if(delManagerDto.getWxidList()==null||delManagerDto.getWxidList().isEmpty()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //通过查询运营商其他索引分片获取分片索引
        String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
        uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, delManagerDto.getMerId());
        Map<String,Object> dataMp_group = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, delManagerDto.getGroupId(), null);
        EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_group)), EsWxContacts.class);
        if(esWxContacts == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信群不存在");
        }

        WxGroupMemberSetAdminDto wxGroupMemberSetAdminDto=new WxGroupMemberSetAdminDto();
        wxGroupMemberSetAdminDto.setMerId(delManagerDto.getMerId());
        wxGroupMemberSetAdminDto.setGroupId(delManagerDto.getGroupId());
        wxGroupMemberSetAdminDto.setOptType(2);
        wxGroupMemberSetAdminDto.setIdList(delManagerDto.getWxidList());
        setAdmin(wxGroupMemberSetAdminDto);
    }
}
